//
//  PolygonView.m
//  HelloPoly
//
//  Created by George Tso on 10/21/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "PolygonView.h"

@implementation PolygonView

- (void)drawRect:(CGRect)rect {
	CGContextRef context =	UIGraphicsGetCurrentContext();
	
	// draw rect
	[[UIColor grayColor] set];
	UIRectFill(self.bounds);
	[[UIColor blackColor] set];
	UIRectFrame(self.bounds);
	
	NSArray *pointsArray =[PolygonView pointsForPolygonInRect:self.bounds numberOfSides:polygon.numberOfSides];
	// drawing polygon
	CGContextBeginPath(context);
	NSValue *aValue = [[NSValue alloc] init];
	aValue = [pointsArray objectAtIndex:0];
	CGContextMoveToPoint(context, [aValue CGPointValue].x, [aValue CGPointValue].y);
	for (int i=1; i<polygon.numberOfSides; i++) {
		NSValue *bValue = [pointsArray objectAtIndex:i];
		CGContextAddLineToPoint(context, [bValue CGPointValue].x, [bValue CGPointValue].y);
	}
	CGContextClosePath(context);
	// color the stroke
	[[UIColor whiteColor] setFill];
	[[UIColor redColor] setStroke];
	CGContextDrawPath(context, kCGPathFillStroke);
}



+ (NSArray *)pointsForPolygonInRect:(CGRect)rect numberOfSides:(int)numberOfSides { 
	CGPoint center = CGPointMake(rect.size.width / 2.0, rect.size.height / 2.0); 
	float radius = 0.9 * center.x; 
	NSMutableArray *result = [NSMutableArray array]; 
	float angle = (2.0 * M_PI) / numberOfSides; 
	float exteriorAngle = M_PI - angle; 
	float rotationDelta = angle - (0.5 * exteriorAngle); 
	
	for (int currentAngle = 0; currentAngle < numberOfSides; currentAngle++) { 
		float newAngle = (angle * currentAngle) - rotationDelta; 
		float curX = cos(newAngle) * radius; 
		float curY = sin(newAngle) * radius; 
		[result addObject:[NSValue valueWithCGPoint:CGPointMake(center.x + curX, 
																center.y + curY)]]; 
	} 
	
	return result; 
}


- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // Initialization code
    }
    return self;
}


- (void)dealloc {
	[polygon release];
    [super dealloc];
}


@end
